package com.zmm.myyimixian.ui.activity.main.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zmm.myyimixian.MyApp;
import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseActivity;
import com.zmm.myyimixian.bean.HomeGoods;
import com.zmm.myyimixian.config.ConfigPath;
import com.zmm.myyimixian.db.DataDao;
import com.zmm.myyimixian.db.ShoppingCart;
import com.zmm.myyimixian.util.UIManager;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;


public class ListViewOneActivity extends BaseActivity implements View.OnClickListener {

    private String url;
    private TextView xl_name_tv;
    private TextView xl_fname_tv;
    private TextView zhrmb_tv;
    private TextView drtg_tv;
    private ImageView tpsbf_iv;
    private ConvenientBanner convenientBanner;
    private MyHandler handler = new MyHandler(this);
    private ImageView smail_onelist_iv;
    private ImageView pj_iv;
    private RadioGroup listone_rg;
    private RadioButton twxq_rb;
    private RadioButton yhpj_rb;
    private TextView gone_tv;
    private RelativeLayout rl;
    private ImageView efhsy_iv;
    private LinearLayout listviewone_jj_ll;
    private TextView listviewone_count_tv;
    private long count = 0;
    private String title;
    //保存状态
    private boolean isBaoCun = false;
    //转换类型
    private String jiaj;



    @Override
    protected void initView() {
        initData();
        //相对布局
        rl = (RelativeLayout) findViewById(R.id.activity_list_view);
        //小图片
        smail_onelist_iv = (ImageView) findViewById(R.id.esmail_onelist_iv);
        //品级
        pj_iv = (ImageView) findViewById(R.id.pj_iv);
        //图文说明和评价
        listone_rg = (RadioGroup) findViewById(R.id.listone_rg);
        twxq_rb = (RadioButton) findViewById(R.id.twxq_rb);
        yhpj_rb = (RadioButton) findViewById(R.id.yhpj_rb);
        //标题
        xl_name_tv = (TextView) findViewById(R.id.exl_name_tv);
        //副标题
        xl_fname_tv = (TextView) findViewById(R.id.exl_fname_tv);
        //价格
        zhrmb_tv = (TextView) findViewById(R.id.ezhrmb_tv);
        //返回
        findViewById(R.id.efanhui_iv).setOnClickListener(this);
        //分享
        findViewById(R.id.egb_iv).setOnClickListener(this);
        //商城
        findViewById(R.id.ewf_tv).setOnClickListener(this);
        //购物车
        efhsy_iv = (ImageView) findViewById(R.id.efhsy_iv);
        efhsy_iv.setOnClickListener(this);
        //评价
        gone_tv = (TextView) findViewById(R.id.gone_tv);
        //加入购物车
        drtg_tv = (TextView) findViewById(R.id.edrtg_tv);
        //图片上部分
        tpsbf_iv = (ImageView) findViewById(R.id.etpsbf_iv);
        //加减的线性布局
        listviewone_jj_ll = (LinearLayout) findViewById(R.id.listviewone_jj_ll);
        //减
        findViewById(R.id.listviewone_jian_iv).setOnClickListener(this);
        //加
        findViewById(R.id.listviewone_jia_iv).setOnClickListener(this);
        //数量
        listviewone_count_tv = (TextView) findViewById(R.id.listviewone_count_tv);

        //轮播
        convenientBanner = (ConvenientBanner) findViewById(R.id.econvenientBanner);
        new MyListViewActivityThread(handler, url).start();
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //商城
            case R.id.ewf_tv:
                UIManager.startMain(this);
                break;
            //购物车
            case R.id.efhsy_iv:
                if (MyApp.isLogin()) {
                    UIManager.startShoppingCartActivity(this);
                } else {
                    UIManager.startLoginActivity(this);
                }
                break;
            //返回
            case R.id.efanhui_iv:
                finish();
                break;
            //分享
            case R.id.egb_iv:
//设置分享的平台
                SHARE_MEDIA[] list = new SHARE_MEDIA[]{SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.DOUBAN, SHARE_MEDIA.EMAIL, SHARE_MEDIA.SMS, SHARE_MEDIA.RENREN, SHARE_MEDIA.YNOTE
                };

                new ShareAction(ListViewOneActivity.this)
                        .setDisplayList(list)//设置分享的平台列表
                        .withText("分享的内容")//分享的内容
                        .withTitle("分享的标题")//分享的标题
                        .withMedia(new UMImage(this, R.mipmap.ic_launcher))//多媒体:图片,音频,视频,表情等
                        //.withTargetUrl(url)//分享一个链接
                        //.addButton()
                        .setCallback(umShareListener)//分享的监听
                        .open();//打开分享面板
                break;
            //数量加1
            case R.id.listviewone_jia_iv:
                ++count;
                if (!isBaoCun){
                    isBaoCun = true;
                }
                jiaj = String.valueOf(count);
                listviewone_count_tv.setText(jiaj);
                break;
            //数量减一
            case R.id.listviewone_jian_iv:
                --count;
                if (!isBaoCun){
                    isBaoCun = true;
                }
                jiaj = String.valueOf(count);
                if (count < 1){
                    isBaoCun = false;
                    count = 0;
                    listviewone_jj_ll.setVisibility(View.GONE);
                    drtg_tv.setVisibility(View.VISIBLE);
                    DataDao.deleteShoppingCart(title, new DeleteListener() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });
                    return;
                }
                listviewone_count_tv.setText(jiaj);
                break;
        }
        //更新商品数量
        if (isBaoCun){
            isBaoCun = false;
            DataDao.setShoppingCart(title, jiaj);
        }
    }

    //回调监听
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(ListViewOneActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ListViewOneActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ListViewOneActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    //接收另一个页面传来的数据和初始化数据
    private void initData() {
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_list_view_one;
    }

    //实现图片轮播
    private void initData(List<String> img_url) {
        convenientBanner.setPages(new CBViewHolderCreator<ListViewOneActivity.ViewPagerImage>() {
            @Override
            public ListViewOneActivity.ViewPagerImage createHolder() {
                return new ListViewOneActivity.ViewPagerImage();
            }
        }, img_url).setPageIndicator(new int[]{R.mipmap.order_list_orange_ball_invalid, R.mipmap.order_list_orange_ball})
                .setPageIndicatorAlign(
                        ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
    }

    //ImageView创建和下载并显示图片
    public class ViewPagerImage implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        //下载轮播图片并显示出来
        @Override
        public void UpdateUI(Context context, final int position, String data) {
            Glide.with(ListViewOneActivity.this).load(ConfigPath.getLunBoPath(data)).placeholder(R.mipmap.icon_home_item_default).into(imageView);
        }
    }

    //重写 onResume onPause 设置自动播放
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(2000);
        //登录成功后在数据库中查找数据
        if (MyApp.isLogin()) {
            new MyListViewActivityThread(handler, url).start();
        }
    }

    //重写onPause方法 设置停止翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止自动翻页
        convenientBanner.stopTurning();
    }


    //获取网上下载的数据
    private class MyHandler extends Handler {

        private WeakReference<ListViewOneActivity> reference = null;

        public MyHandler(ListViewOneActivity listViewActivity) {
            reference = new WeakReference<>(listViewActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ListViewOneActivity listViewActivity = reference.get();
            if (listViewActivity != null) {
                if (msg.what == 1) {
                    HomeGoods goods = (HomeGoods) msg.obj;
                    HomeGoods.GoodDetailBean.GoodBean good = goods.getGood_detail().getGood();
                    List<String> img_url = good.getImg_url();
                    initData(img_url);
                    initData(good);
                }
            }
        }
    }

    //展示listviewoneacttivity界面
    private void initData(HomeGoods.GoodDetailBean.GoodBean good) {
        final String new_promo_type = good.getNew_promo_type();
        final String img_url = good.getImg_url().get(0).toString();
        Glide.with(this).load(ConfigPath.getLunBoPath(new_promo_type)).placeholder(R.mipmap.icon_home_item_default).into(smail_onelist_iv);
        title = good.getTitle();
        xl_name_tv.setText(title);
        final String unit_desc = good.getUnit_desc();
        xl_fname_tv.setText(unit_desc + "  产地：" + good.getProductby());
        String unit_desc1 = unit_desc.substring(0, 2);
        if ("A级".equals(unit_desc1)) {
            pj_iv.setImageDrawable(getResources().getDrawable(R.mipmap.good_level_1));
        } else if ("B级".equals(unit_desc1)) {
            pj_iv.setImageDrawable(getResources().getDrawable(R.mipmap.good_level_0));
        } else if ("AA".equals(unit_desc1)) {
            pj_iv.setImageDrawable(getResources().getDrawable(R.mipmap.good_level_2));
        } else if ("传奇".equals(unit_desc1)) {
            pj_iv.setImageDrawable(getResources().getDrawable(R.mipmap.good_level_4));
        } else if ("甄鲜".equals(unit_desc1)) {
            pj_iv.setImageDrawable(getResources().getDrawable(R.mipmap.good_level_3));
        }
        final String unit_price = good.getUnit_price();
        zhrmb_tv.setText(unit_price);
        List<HomeGoods.GoodDetailBean.GoodBean.FunctionNewImgurlBean> function_new_imgurl = good.getFunction_new_imgurl();
        Glide.with(this).load(ConfigPath.getLunBoPath(function_new_imgurl.get(0).getUrl())).placeholder(R.mipmap.icon_home_item_default).into(tpsbf_iv);
        final String count_zero_reason = good.getCount_zero_reason();
        if (!"".equals(count_zero_reason)){
            drtg_tv.setBackgroundColor(Color.parseColor("#C8C8C8"));
        }
        //监听
        listone_rg.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        if (MyApp.isLogin()) {
            DataDao.getShoppingCart(title, new FindListener<ShoppingCart>() {
                @Override
                public void onSuccess(List<ShoppingCart> list) {
                    if (list.size() > 0) {
                        drtg_tv.setVisibility(View.GONE);
                        listviewone_jj_ll.setVisibility(View.VISIBLE);
                        String count1 = list.get(0).getCount();
                        count = Long.valueOf(count1);
                        listviewone_count_tv.setText(count1);
                    }
                }

                @Override
                public void onError(int i, String s) {

                }
            });
        }
        //第一个添加
        drtg_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"".equals(count_zero_reason)){
                    Toast.makeText(ListViewOneActivity.this, count_zero_reason, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (MyApp.isLogin()) {
                    DataDao.addShoppingCart(img_url, title, unit_desc, unit_price, "1", new_promo_type, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            drtg_tv.setVisibility(View.GONE);
                            listviewone_jj_ll.setVisibility(View.VISIBLE);
                            count = 1;
                            listviewone_count_tv.setText("1");
                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });
                } else {
                    UIManager.startLoginActivity(ListViewOneActivity.this);
                }
            }
        });
    }

    //图文和评价切换
    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.twxq_rb:
                    twxq_rb.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    yhpj_rb.setBackgroundColor(Color.parseColor("#F0F0F0"));
                    gone_tv.setVisibility(View.GONE);
                    tpsbf_iv.setVisibility(View.VISIBLE);
                    break;
                case R.id.yhpj_rb:
                    yhpj_rb.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    twxq_rb.setBackgroundColor(Color.parseColor("#F0F0F0"));
                    gone_tv.setVisibility(View.VISIBLE);
                    tpsbf_iv.setVisibility(View.GONE);
                    break;
            }
        }
    }
}
